package com.example.adminbase.mybatisinterceptor;

import com.example.adminbase.domain.QueryParam;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ResultMapping;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.scripting.defaults.DefaultParameterHandler;

import java.lang.reflect.Field;
import java.sql.PreparedStatement;
import java.util.List;
import java.util.Properties;

//todo: 完善拦截器
@Intercepts(value = @Signature(type = ParameterHandler.class, method = "setParameters", args = {PreparedStatement.class}))
public class SortFieldParamInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        DefaultParameterHandler target = (DefaultParameterHandler) invocation.getTarget();
        Field mappedStatementField = target.getClass().getDeclaredField("mappedStatement");
        boolean accessible = mappedStatementField.isAccessible();
        mappedStatementField.setAccessible(true);
        MappedStatement mappedStatement = (MappedStatement) mappedStatementField.get(target);
        mappedStatementField.setAccessible(accessible);

        Object parameterObject = target.getParameterObject();
        if(parameterObject instanceof QueryParam) {
            List<String> tableSorts = ((QueryParam) parameterObject).getTableSorts();
            List<ResultMapping> resultMappings = mappedStatement.getResultMaps().get(0).getResultMappings();
//            Optional<ResultMapping> optional = resultMappings.stream().filter(resultMapping -> resultMapping.getProperty().equals("")).findFirst();
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
